package com.atguigu.flinkState;

import com.atguigu.been.WaterSensor;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.AggregatingState;
import org.apache.flink.api.common.state.AggregatingStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @author wky
 * @create 2021-07-19-9:35
 */
//AggregatingState 输入输出类型不同	计算每个传感器的平均水位
public class State_Keyed_AggregatingState {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment senv = StreamExecutionEnvironment.getExecutionEnvironment();

        senv.setParallelism(1);
        DataStreamSource<String> source = senv.socketTextStream("hadoop102", 9999);
        SingleOutputStreamOperator<WaterSensor> map = source.map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String value) throws Exception {
                String[] split = value.split(",");
                return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
            }
        });
        KeyedStream<WaterSensor, String> keyedStream = map.keyBy(WaterSensor::getId);
        //计算每个传感器的水位和
        keyedStream.process(new KeyedProcessFunction<String, WaterSensor, String>() {
            //设置状态值
            private AggregatingState<Integer,Double> agg;

            @Override
            public void open(Configuration parameters) throws Exception {
                //初始化  写入逻辑    防止空指针异常 加载时间的问题
                agg = getRuntimeContext().getAggregatingState(new AggregatingStateDescriptor<Integer, Tuple2<Integer,Integer>, Double>("agg", new AggregateFunction<Integer, Tuple2<Integer, Integer>, Double>() {
                    //创建累加器
                    @Override
                    public Tuple2<Integer, Integer> createAccumulator() {
                        return Tuple2.of(0,0);
                    }

                    @Override
                    //累加操作
                    public Tuple2<Integer, Integer> add(Integer value, Tuple2<Integer, Integer> accumulator) {
                        return Tuple2.of(accumulator.f0+value,accumulator.f1+1);
                    }

                    @Override
                    //返回结果
                    public Double getResult(Tuple2<Integer, Integer> accumulator) {
                        return accumulator.f0*1D/accumulator.f1;
                    }

                    //合并累加器
                    @Override
                    public Tuple2<Integer, Integer> merge(Tuple2<Integer, Integer> a, Tuple2<Integer, Integer> b) {
                       return Tuple2.of(a.f0 + b.f0, a.f1 + b.f1);
                    }
                }, Types.TUPLE(Types.INT, Types.INT)));
            }

            @Override
            public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                agg.add(value.getVc());
                out.collect(agg.get().toString());
            }
        }).print();
        senv.execute();


    }
}
